package cn.sylinx.horm.resource.parse;

import java.util.Map;

import cn.sylinx.horm.exception.HORMException;

public final class OriginalContentPlaceholderParser {

    public static final OriginalContentPlaceholderParser INSTANCE = new OriginalContentPlaceholderParser();

    private final String startSymbol = "${"; // 开始占位符
    private final String endSymbol = "}"; // 结束占位符

    private OriginalContentPlaceholderParser() {
    }

    public String parseSql(String sql, Map<String, Object> env) {

        if (sql == null) {
            throw new HORMException("sql is null");
        }

        int is = sql.indexOf(startSymbol);
        if (is == -1) {
            return sql;
        }

        StringBuilder preparedStatement = new StringBuilder();
        parseSqlInner(sql, env, preparedStatement);
        return preparedStatement.toString();
    }

    private void parseSqlInner(String sql, Map<String, Object> env, StringBuilder preparedStatement) {

        int is = sql.indexOf(startSymbol);
        if (is == -1) {
            preparedStatement.append(sql);
            return;
        }

        String tmp = sql.substring(is);
        int is1 = tmp.indexOf(endSymbol);
        int ie = is1 + is;
        if (is1 == -1) {
            throw new HORMException("illegal statement");
        }

        String split = sql.substring(is + startSymbol.length(), ie);
        String originalContent = getContent(split, env);

        String before = sql.substring(0, is) + originalContent;
        preparedStatement.append(before);
        String after = sql.substring(ie + endSymbol.length());

        parseSqlInner(after, env, preparedStatement);
    }

    private String getContent(String key, Map<String, Object> env) {
        Object param = env.get(key);
        if (param == null) {
            return "";
        }
        return param.toString();
    }

}
